package com.模拟线程安全问题.Lock的锁;


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.concurrent.locks.ReentrantLock;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account {
    private String userID;
    private Double money;

    //创建锁的对象
    private static final ReentrantLock lock = new ReentrantLock();


    //取钱的方法
    public void getMoney(Double money) {
//1.先来判断是谁取钱
        String name = Thread.currentThread().getName();
        //加锁
        lock.lock();
        //2.判断账户是否余额足够
        try {
            if (this.money >= money) {
                System.out.println(name + "取走了" + money);
                //更新账户余额
                this.money -= money;
                System.out.println(name + "取钱后剩余" + this.money);
            } else {
                System.out.println(name + "余额不足!");
            }
        } finally {
            //解锁
            lock.unlock();
        }
    }

}
